﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpSoft.Documentation.Html.CSS
{
    /// <summary>
    /// 描述CSS选择器
    /// </summary>
    public class CssSelector
    {
        public CssSelector(IRule[] rules)
        {
            _Rules = rules;
        }
        private IRule[] _Rules;
        /// <summary>
        /// 获取当前选择器的所有规则
        /// </summary>
        public IRule[] Rules
        {
            get { return _Rules; }
            set { _Rules = value; }
        }
        /// <summary>
        /// 当前选择器是否为空
        /// </summary>
        public bool IsEmpty
        {
            get
            {
                return Rules.Length == 0;
            }
        }

    }
    /// <summary>
    /// 用于构建选择器
    /// </summary>
    public class SelectorBuilder
    {
        private List<IRule> rules;

        private IRule lastRule;
        public SelectorBuilder()
        {
            rules = new List<IRule>();
        }

        public void Clear()
        {
            rules.Clear();
        }

        /// <summary>
        /// 添加一个规则
        /// </summary>
        /// <param name="rule"></param>
        /// <returns></returns>
        internal SelectorBuilder AddRule(IRule rule)
        {
            rules.Add(rule);
            lastRule = rule;
            return this;
        }

        internal SelectorBuilder AddFrameRule(string framename)
        {
            return this.AddRule(new FrameRule(framename));
        }
        internal SelectorBuilder AddPseudoClassRule(string pseudoname, string para = null)
        {
            return this.AddRule(new PseudoClassRule(pseudoname, para));
        }
        internal SelectorBuilder AddClassRule(string classname)
        {
            return this.AddRule(new ClassRule(classname));
        }
        internal SelectorBuilder AddTagRule(string tagname)
        {
            return this.AddRule(new TagRule(tagname));
        }
        internal SelectorBuilder AddIdRule(string id)
        {
            return this.AddRule(new IdRule(id));
        }
        internal SelectorBuilder AddAttributeRule(string attname, string attvalue = null, AttributeMatchType matchtype = AttributeMatchType.Equal)
        {
            return this.AddRule(new AttributeRule(attname, attvalue, matchtype));
        }

        /// <summary>
        /// 设置上一次添加的规则与其下一个规则的关系类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        internal SelectorBuilder SetRuleRelation(CssSelectorRuleRelationType type)
        {
            if (lastRule == null)
                throw new Exception("在添加一个规则之前无法设置规则的关系。");
            lastRule.RelationType = type;
            return this;
        }

        /// <summary>
        /// 使用当前构造器中的内容构建一个Selector
        /// </summary>
        /// <returns></returns>
        public CssSelector GetSelector()
        {
            return new CssSelector(rules.ToArray());
        }

    }
}
